package com.avic.modules.backup4MySQL.config;

import com.avic.modules.backup4MySQL.MySQLBackup;
import com.avic.modules.quartz.domain.QuartzJob;
import com.avic.modules.quartz.service.QuartzJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Slf4j
@Configuration
public class BackupConfig {


    private final QuartzJobService quartzJobService;


    @Value("${spring.datasource.druid.name}")
    private String dbName;

    @Value("${spring.datasource.druid.username}")
    private  String userName;

    @Value("${spring.datasource.druid.password}")
    private  String password;

    @Value("${spring.datasource.druid.url}")
    private  String jdbcConnUrl;

    @Value("${spring.datasource.druid.driver-class-name}")
    private  String driverClassName;

    public BackupConfig(QuartzJobService quartzJobService) {
        this.quartzJobService = quartzJobService;
    }

    @Bean
    public void doBackupJobDefault(){

        List<QuartzJob> quartzJobList = quartzJobService.checkBackupJob();
        if (quartzJobList.size() == 0){
            QuartzJob quartzJob = new QuartzJob();
            quartzJob.setBeanName("mySQLBackupTask");
            quartzJob.setMethodName("runMySQLDump");
            quartzJob.setRemark("daily backup job,don't delete");
            quartzJob.setJobName("doFixedTimeBackupTask 数据库定时备份 Default");
            quartzJob.setIsPause(false);
            /**
             * 默认每天 18 点备份一次
             */
            quartzJob.setCronExpression("0 0 18 * * ?");
            if (quartzJobService.save(quartzJob)) {
                log.info("创建定时备份任务入库 ：[ quartz job name = {} ]", quartzJob.getJobName());
            }else{
                throw new RuntimeException("默认创建备份任务失败");
            }
        }else{
            QuartzJob quartzJob = quartzJobList.get(0);
            if(quartzJob.getIsPause()){
                quartzJob.setIsPause(false);
                quartzJobService.updateById(quartzJob);
            }
            log.info("【------------定时备份任务正常------------】");
        }
    }

    @Bean
    public MySQLBackup mySQLBackup(){
        MySQLBackup mySQLBackup = new MySQLBackup();
        mySQLBackup.init(dbName,userName,password,jdbcConnUrl,driverClassName);
        return mySQLBackup;
    }
}
